/*
 *  Copyright (C) 2010 takaji
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package examples.helpers;

import java.text.MessageFormat;

import dakside.csv.CSVFileReader;
import dakside.csv.CSVFileWriter;
import dakside.csv.CSVLine;

/**
 * CSV worker
 * @author Takaji
 */
public class Worker implements Runnable {

    private CSVFileReader reader = null;
    private CSVFileWriter writer = null;
    private String name = "";
    private boolean report = false;
    private int i = 0;

    /**
     * Constructor
     * @param name worker's name
     * @param reader
     * @param writer
     * @param report true to report each line processed
     */
    public Worker(String name, CSVFileReader reader, CSVFileWriter writer,
            boolean report) {
        this.name = name;
        this.reader = reader;
        this.writer = writer;
        this.report = report;
        say("I'm alive");
    }

    /**
     * Say something
     * @param message
     */
    private void say(String message){
	System.out.println(MessageFormat.format("[{0}] {1}", name, message));
    }

    @Override
    public void run() {
	say("I'm running");
        CSVLine line = reader.readLine();

        while (line != null) {
            //process line
            process(line);

            if (this.report) {
                // push to console
                System.out.println(CSVDump.getLineText(line));
            }
            // write to writer
            writer.writeLine(line);
            //continue to read next line
            line = reader.readLine();
        }
        say("I'll flush writer now");
        writer.flush();
        say("I finished. I've processed " + i + " lines.");
    }

    /**
     * Process the line
     * @param line
     */
    private void process(CSVLine line) {
        // sample processing
        line.add("Processed by " + name);
        i++;
    }
}
